package com.fulicarpet.shop.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.fulicarpet.shop.bean.WxLoginBean;
import com.fulicarpet.shop.config.Api;
import com.fulicarpet.shop.config.Constants;
import com.fulicarpet.shop.event.WxEvent;
import com.fulicarpet.shop.utils.JsonParseUtils;
import com.fulicarpet.shop.utils.ToastUtils;
import com.alibaba.fastjson.JSONObject;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.weixin.view.WXCallbackActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.net.URLEncoder;

import okhttp3.Call;

public class WXEntryActivity extends WXCallbackActivity implements IWXAPIEventHandler{
    private IWXAPI api;
    private String result = "";

    // 获取第一步的code后，请求以下链接获取access_token
    private String GetCodeRequest = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    // 获取用户个人信息
    private String GetUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID, false);
        api.handleIntent(getIntent(), this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        Log.i("req", req.openId);
        finish();
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                switch (resp.getType()) {
                    case ConstantsAPI.COMMAND_SENDAUTH:
                        if (result.equals("")){
                            result = "发送成功";
                            ToastUtils.showShort(WXEntryActivity.this, result);
                            //登录回调,处理登录成功的逻辑
                            String code = ((SendAuth.Resp) resp).code;
                            //将AppID、AppSecret、code，拼接成URL 获取access_token等等的信息(微信)
                            String url = getCodeRequest(code);
                            getAccessToken(url);
                            finish();
                        }
                        break;
                    case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
                        //分享回调,处理分享成功后的逻辑
                        super.onResp(resp);//一定要加super，实现我们的方法，否则不能回调
                        finish();
                        break;
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "发送取消";
                ToastUtils.showShort(this, result);
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "发送拒绝";
                ToastUtils.showShort(this, result);
                finish();
                break;
            default:
                result = "发送返回";
                ToastUtils.showShort(this, result);
                finish();
                break;
        }
    }

    /**
     * 拼接成URL 获取access_token
     * @param url
     */
    private void getAccessToken(String url){
        OkHttpUtils.post().url(url)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("WXEntry",e.getMessage());
                ToastUtils.showShort(WXEntryActivity.this, "登录失败");
            }

            @Override
            public void onResponse(String response, int id) {
                JsonParseUtils instance = JsonParseUtils.getInstance(response);
                JSONObject object = instance.getObject();
                String accessToken = object.getString("access_token");
                String openId = object.getString("openid");
                if (accessToken!=null&&!accessToken.equals("")){
                    String userInfoUrl = getUserInfoUrl(accessToken, openId);
                    getUserInfo(userInfoUrl, accessToken);
                }else{
                    Log.e("WXEntry","response:"+response);
                    ToastUtils.showShort(WXEntryActivity.this, "登录失败");
                }
            }
        });
    }

    /**
     * 通过拼接的用户信息url获取用户信息
     * @param userInfoUrl
     */
    private void getUserInfo(String userInfoUrl, final String accessToken) {
        OkHttpUtils.post().url(userInfoUrl)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showShort(WXEntryActivity.this, "登录失败");
            }

            @Override
            public void onResponse(String response, int id) {
                JsonParseUtils instance = JsonParseUtils.getInstance(response);
                JSONObject object = instance.getObject();
                String unionId = object.getString("unionid");
                String openid = object.getString("openid");
                String nickname = object.getString("nickname");
                String headImgUrl = object.getString("headimgurl");
                String sex = object.getString("sex");
                loginToOur(unionId,openid, accessToken, headImgUrl, nickname, sex);
            }
        });
    }

    private void loginToOur(String unionId,String openid, String access_token, String headImgUrl, String nickname, String sex) {
        OkHttpUtils.post().url(Api.AUTH_LOGIN)
                .addParams("bind_id",unionId)
                .addParams("access_token",access_token)
                .addParams("openid",openid)
                .addParams("bind_avator",headImgUrl)
                .addParams("bind_nickname",nickname)
                .addParams("bind_gender",sex)
                .addParams("type","weixin")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showShort(WXEntryActivity.this, "登录失败");
            }
            @Override
            public void onResponse(String response, int id) {
                JsonParseUtils instance= JsonParseUtils.getInstance(response);
                if (instance.parseStatus()){
                    JSONObject data = instance.parseData();
                    WxLoginBean wxLoginBean = new WxLoginBean(data.getString("ut"), data.getString("us"), data.getString("at"));
                    EventBus.getDefault().post(new WxEvent(3,wxLoginBean));
                }else{
                    ToastUtils.showShort(WXEntryActivity.this, "登录失败");
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        finish();
    }

    /**
     * 获取access_token的URL（微信）
     * @param code 授权时，微信回调给的
     * @return URL
     */
    private String getCodeRequest(String code) {
        String result = null;
        GetCodeRequest = GetCodeRequest.replace("APPID", urlEnodeUTF8(Constants.WX_APP_ID));
        GetCodeRequest = GetCodeRequest.replace("SECRET", urlEnodeUTF8(Constants.WX_APP_SECRET));
        GetCodeRequest = GetCodeRequest.replace("CODE", urlEnodeUTF8(code));
        result = GetCodeRequest;
        return result;
    }

    /**
     * 获取用户个人信息的URL（微信）
     * @param access_token 获取access_token时给的
     * @param openid       获取access_token时给的
     * @return URL
     */
    private String getUserInfoUrl(String access_token, String openid) {
        String result = null;
        GetUserInfo = GetUserInfo.replace("ACCESS_TOKEN", urlEnodeUTF8(access_token));
        GetUserInfo = GetUserInfo.replace("OPENID", urlEnodeUTF8(openid));
        result = GetUserInfo;
        return result;
    }

    private String urlEnodeUTF8(String str) {
        String result = str;
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}